package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        //queryWithPassThough(id);
        //使用工具类解决缓存穿透
        //Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_TTL, TimeUnit.MINUTES, CACHE_SHOP_KEY, id, Shop.class, this::getById);
        //使用互斥锁解决缓存击穿
        //Shop shop = queryWithMutex(id);
        //使用逻辑过期时间解决缓存击穿
        //Shop shop = queryWithLogicalExpire(id);
        //使用工具类的逻辑过期时间解决缓存击穿
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, 20L, TimeUnit.SECONDS);
        if (shop == null) {
            return Result.fail("店铺不存在!");
        }

        return Result.ok(shop);
    }
    //创建线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    private Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //根据id从redis中查询商铺缓存
        String shopJson = redisTemplate.opsForValue().get(key);
        //判断缓存是否命中
        if (StrUtil.isBlank(shopJson)) {
            //如果redis缓存未命中.返回空值
            return null;
        }
        //命中，判断过期时间，需要把json字符串反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        //因为RedisData中使用的数据是object，所以要强转为JSONObject类型，然后传入实际的数据类型
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())){
            //未过期，直接返回店铺信息
            return shop;
        }
        //如果过期,需要缓存重建
        //获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        //判断获取锁是否成功，如果成功，开启独立线程实现缓存重建
        boolean isLock = tryLock(lockKey);
        if (isLock){
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //重建缓存
                    this.save2(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放互斥锁
                    unlock(lockKey);
                }
            });
        }
        //如果获取锁失败，直接返回过期的数据
        //返回结果
        return shop;
    }

    private boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, "", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    //封装缓存穿透逻辑
    public Shop queryWithPassThough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //根据id从redis中查询商铺缓存
        String shopJson = redisTemplate.opsForValue().get(key);
        //判断缓存是否命中
        if (StrUtil.isNotBlank(shopJson)) {
            //如果redis缓存直接命中，就返回商铺信息.
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断缓存命中的是否是空值(因为缓存已经命中，所以缓存里面就只有两种情况：1.null 2.空字符串)
        //如果不等于null，就一定是空字符串
        if (shopJson != null) {
            //直接返回错误信息
            return null;
        }
        //如果redis缓存未命中，根据id查询数据库
        Shop shop = getById(id);
        //判断数据库中的商铺信息是否存在，如果存在写入到redis缓存，不存在返回错误信息
        if (shop == null) {
            //如果shop信息不存在，就缓存一个空值，防止缓存穿透
            redisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //返回结果
        return shop;
    }

    //互斥锁解决缓存穿透
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //根据id从redis中查询商铺缓存
        String shopJson = redisTemplate.opsForValue().get(key);
        //判断缓存是否命中
        if (StrUtil.isNotBlank(shopJson)) {
            //如果redis缓存直接命中，就返回商铺信息.
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //判断缓存命中的是否是空值(因为缓存已经命中，所以缓存里面就只有两种情况：1.null 2.空字符串)
        //如果不等于null，就一定是空字符串
        if (shopJson != null) {
            //直接返回错误信息
            return null;
        }
        // 实现缓存重建
        // 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);
            // 判断是否获取成功，如果失败，休眠并重试
            if (!isLock) {
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            // 如果成功，根据id查询数据库
            shop = getById(id);
            //模拟重建的延时
            Thread.sleep(200);
            //判断数据库中的商铺信息是否存在，如果存在写入到redis缓存，不存在返回错误信息
            if (shop == null) {
                //如果shop信息不存在，就缓存一个空值，防止缓存穿透
                redisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //存在，写入redis
            redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放互斥锁
            unlock(lockKey);
        }
        //返回结果
        return shop;
    }

    //缓存热点key实现缓存预热
    public void save2(Long id, Long expireTime) throws InterruptedException {
        //查询店铺信息
        Shop shop = getById(id);
        Thread.sleep(200);
        //封装为逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        //写入redis
        redisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空!");
        }
        //先更新数据库
        updateById(shop);
        //删除缓存
        redisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1. 判断是否需要根据坐标进行查询
        if (x == null && y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            return Result.ok(page.getRecords());
        }

        //2. 计算分页参数
        String key = SHOP_GEO_KEY + typeId;
        int from = (current-1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;
        //3. 查询redis geo中的数据，按照距离进行排序，分页；结果：shopId，distance
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo()
                .radius(key, new Circle(x, y, new Distance(5000).getValue()),
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end));
        if (results == null){
            return Result.ok(Collections.emptyList());
        }
        //解析数据 解析出店铺ids，distance
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from){
            //没有下一页了
            return Result.ok(Collections.emptyList());
        }
        ArrayList<Long> ids = new ArrayList<>(list.size());
        HashMap<String, Distance> map = new HashMap<>(list.size());
        //截取from - end的部分
        list.stream().skip(from).forEach(result ->{
            String shopIdStr = result.getContent().getName();
            ids.add(Long.valueOf(shopIdStr));
            Distance distance = result.getDistance();
            map.put(shopIdStr,distance);

        });
        //4. 查询店铺。返回结果
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
